package com.lemon.system.service.impl;

import com.lemon.core.consts.ApiConstant;
import com.lemon.core.web.Result;
import com.lemon.mybatisplus.base.BaseServiceImpl;
import com.lemon.mybatisplus.enums.DeleteEnum;
import com.lemon.mybatisplus.enums.StatusEnum;
import com.lemon.security.dto.LoginUserDetail;
import com.lemon.security.utils.JwtUtil;
import com.lemon.system.dao.TenantMenuDAO;
import com.lemon.system.dto.TenantMenuDTO;
import com.lemon.system.po.TenantMenuPO;
import com.lemon.system.service.ITenantMenuService;
import com.lemon.system.vo.LeftMenuVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.groupingBy;

/**
 * 租户-菜单中间表 业务实现类
 *
 * @author 李猛
 * @since 2024-02-11
 */
@Log4j2
@Service
public class TenantMenuServiceImpl extends BaseServiceImpl<TenantMenuDAO, TenantMenuPO, TenantMenuDTO> implements ITenantMenuService {
    @Override
    public Result<List<LeftMenuVO>> getLeftMenu() {
        //1.当前登录的用户信息
        LoginUserDetail currentUser = JwtUtil.getCurrentUser();

        //2.查询菜单信息
        Map<String, Object> param = new HashMap<>();
        param.put("userId", currentUser.getUserId());
        param.put("tenantId", currentUser.getTenantId());
        param.put(StatusEnum.ENABLE.getColumn(), StatusEnum.ENABLE.getValue());
        param.put(DeleteEnum.UNABLE.getColumn(), DeleteEnum.UNABLE.getValue());
        List<LeftMenuVO> leftMenuList = this.baseMapper.getLeftMenu(param);
        if (CollectionUtils.isEmpty(leftMenuList)) {
            return Result.ok();
        }

        leftMenuList.forEach(item -> {
            String path = item.getPath().toLowerCase(Locale.CHINA);
            item.setPath(path.endsWith(".vue") ? path.substring(0,path.length() - 4) : path);
        });

        //3.根据 parentId 分组
        Map<Long, List<LeftMenuVO>> listMap = leftMenuList.stream().collect(groupingBy(LeftMenuVO::getParentId));

        //4.给父菜单设置子菜单
        List<LeftMenuVO> childMenuList = new ArrayList<>();
        leftMenuList.forEach(item -> {
            List<LeftMenuVO> menuList = listMap.get(item.getId());
            item.setChildren(menuList);
            if(!CollectionUtils.isEmpty(menuList)){
                childMenuList.addAll(menuList);
            }
        });

        //5.父菜单
        List<LeftMenuVO> parentMenuList = leftMenuList.stream()
                .filter(item -> !childMenuList.contains(item))
                .filter(item -> item.getParentId().equals(ApiConstant.SUPER_PARENT_ID))
                .collect(Collectors.toList());

        //6.合并结果集
        List<LeftMenuVO> result = Stream.concat(parentMenuList.stream(), leftMenuList.stream().filter(item -> !childMenuList.contains(item))).collect(Collectors.toList());
        return Result.ok(result);
    }


}